<template>
  <div class="exam-results">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>考试结果</h3>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <!-- 考试基本信息 -->
      <div class="exam-info">
        <h4>{{ examInfo.examName || examInfo.name }}</h4>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">开始时间：</span>
            <span>{{ examInfo.startTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">结束时间：</span>
            <span>{{ examInfo.endTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">参与人数：</span>
            <span>{{ examInfo.participantCount }}人</span>
          </div>
          <div class="info-item">
            <span class="label">平均分：</span>
            <span>{{ examInfo.averageScore }}分</span>
          </div>
          <div class="info-item">
            <span class="label">最高分：</span>
            <span>{{ examInfo.highestScore }}分</span>
          </div>
          <div class="info-item">
            <span class="label">最低分：</span>
            <span>{{ examInfo.lowestScore }}分</span>
          </div>
        </div>
      </div>

      <!-- 成绩分布图表 -->
      <div class="score-distribution">
        <div ref="chartRef" class="chart"></div>
      </div>

      <!-- 成绩列表 -->
      <div class="score-list">
        <h4 style="margin-bottom: 10px">成绩列表</h4>
        <el-table
            :data="scoreList"
            style="width: 100%"
            border
            v-loading="loading"
            @row-click="handleViewDetail"
        >
          <el-table-column prop="index" width="80" label="序号" sortable/>
          <el-table-column prop="username" label="姓名" min-width="120" sortable/>
          <el-table-column prop="score" label="得分" width="100" sortable>
            <template #default="{ row }">
              <span :class="{ 'text-danger': row.score < 0.6*row.fullScore }">{{
                  row.score
                }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="用时(分钟)" width="120" sortable/>
          <el-table-column prop="beginTime" label="开考时间" width="180" sortable/>
          <el-table-column prop="submitTime" label="提交时间" width="180" sortable/>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 答题详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="答题详情" width="70%">
      <div v-if="currentDetail" class="answer-detail">
        <div class="student-info">
          <p><strong>学生：</strong>{{ currentDetail.username }}</p>
          <p><strong>总分：</strong>{{ currentDetail.score }}</p>
        </div>
        <div class="answer-list">
          <div
            v-for="(answer, index) in currentDetail.answers"
            :key="index"
            class="answer-item"
          >
            <div class="question-header">
              <el-tag
                  :type="getTypeTag(answer.typeId)"
                  class="question-type"
              >
                {{ getTypeText(answer.typeId) }}
              </el-tag>
              <el-rate
                  v-model="answer.difficulty"
                  disabled
                  show-score
                  text-color="#ff9900"
              />
              <span class="question-score">{{ answer.fullScore }}分</span>
              <img v-if="answer.isCorrect===1" class="question-correctPic" src="../../assets/images/correct.png" alt="">
              <img v-else class="question-correctPic" src="../../assets/images/error.png" alt="">
            </div>
            <div class="question-content">{{ index + 1 }}. {{ answer.content }}</div>
            <div v-if="answer.options" class="question-options">
              <div
                  v-for="(option, key) in JSON.parse(answer.options)"
                  :key="key"
                  class="option-item"
              >
                {{ key }}. {{ option }}
              </div>
            </div>
            <div class="question-answer">
              <p><strong>正确答案：</strong>{{ answer.correctAnswer }}</p>
              <p><strong>学生答案：</strong>{{ answer.answer }}</p>
              <p><strong>学生得分：</strong>
                <span class="question-score">{{ answer.score }}分</span>
              </p>
              <p v-if="answer.analysis">
                <strong>解析：</strong>{{ answer.analysis }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from "vue";
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import * as echarts from "echarts";
import {examApi} from "../../api/examApi";
import {getTypeTag, getTypeText} from "../../utils/utils";

const route = useRoute();
const examId = route.params.id;
const loading = ref(false);
const examInfo = ref({});
const scoreList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const detailDialogVisible = ref(false);
const currentDetail = ref(null);
const chartRef = ref(null);
let chart = null;

// 获取考试信息和成绩分布
const getExamInfo = async () => {
  try {
    const res = await examApi.getExamResults(examId);
    // 适配后端返回结构
    const info = res.result.examInfo || {};
    examInfo.value = {
      examName: info.examName,
      name: info.name,
      startTime: info.startTime,
      endTime: info.endTime,
      participantCount: info.attendCount,
      averageScore: info.avgScore,
      highestScore: info.maxScore,
      lowestScore: info.minScore,
    };
    initChart(res.result.scoreDistribution || []);
  } catch (error) {
    console.error("获取考试信息失败:", error);
  }
};

// 获取成绩列表
const getScoreList = async () => {
  loading.value = true;
  try {
    const res = await examApi.getExamScores({
      examId: examId,
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
    });
    // 适配后端返回结构
    scoreList.value = (res.result.data || []).map((item) => ({
      ...item,
    }));
    scoreList.value.forEach((o, index) => {
      o.index = index + 1 + pageSize.value * (currentPage.value - 1);
    })
    total.value = res.result.total || 0;
  } catch (error) {
    console.error("获取成绩列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initChart = (data) => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  const option = {
    title: {
      text: "成绩分布",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: data.map((item) => item.range),
    },
    yAxis: {
      type: "value",
      name: "人数",
    },
    series: [
      {
        data: data.map((item) => item.count),
        type: "bar",
      },
    ],
  };
  chart.setOption(option);
};

// 查看答题详情
const handleViewDetail = async (row) => {
  try {
    const res = await examApi.getExamAnswerDetail(examId, row.resultId);
    currentDetail.value = row;
    currentDetail.value.answers = res.result;

    detailDialogVisible.value = true;
  } catch (error) {
    console.error("获取答题详情失败:", error);
  }
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  getScoreList();
};

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getScoreList();
};

onMounted(() => {
  getExamInfo();
  getScoreList();
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
  }
});
</script>

<style scoped>
.exam-results {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info {
  margin: 0 100px 30px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  margin-right: 10px;
}

.score-distribution {
  margin: 30px 80px 30px 100px;
}

.chart {
  height: 400px;
  margin-top: 20px;
}

.score-list {
  margin: 0 180px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-danger {
  color: #f56c6c;
}

.student-info {
  font-size: 18px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.answer-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  margin-bottom: 10px;
}

.question-type {
  color: #409eff;
  margin-right: 10px;
}

.question-content {
  margin-bottom: 10px;
  line-height: 1.5;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.question-score {
  color: #f56c6c;
  font-weight: bold;
}

.question-type {
  font-size: 16px;
}

.question-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
}

.question-options {
  margin-bottom: 20px;
}

.option-item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.question-answer {
  color: #606266;
  line-height: 1.8;
}

.question-correctPic {
  width: 80px;
  height: 80px;
}
</style>
